<template>
  <page-card title="连接器管理"
             :subTitle="idNum ? '编辑' : '新增'"
             :need-back="true">
    <div class="class_name">
      <a-form-model :model="form"
                    :rules="rules"
                    ref="ruleForm"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                    layout="horizontal">
        <!-- 连接器名称 -->
        <a-form-model-item label="连接器名称"
                           prop="name">
          <a-input v-model="form.name"
                   placeholder="请输入"></a-input>
        </a-form-model-item>
        <!-- 提供方 -->
        <a-form-model-item label="提供方"
                           prop="provider"
                           help="用于标识连接器的提供方名称及业务">
          <a-input v-model="form.provider"
                   placeholder="请输入"></a-input>
        </a-form-model-item>
        <!-- 域名/IP地址 -->
        <a-form-model-item label="域名/IP地址"
                           prop="ipAddr"
                           help="连接器的IP地址或域名，例：http://www.service.com或者http://127.0.0.1">
          <a-input v-model="form.ipAddr"
                   placeholder="请输入"></a-input>
        </a-form-model-item>
        <!-- 请求协议 -->
        <a-form-model-item label="请求协议"
                           prop="requestProtocol">
          <a-radio-group v-model="form.requestProtocol">
            <a-radio value="1">HTTP</a-radio>
            <a-radio value="2">HTTPS</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <!-- baseUrl -->
        <a-form-model-item label="BASE_URL"
                           prop="baseUrl"
                           help="连接器服务的根目录名称，例：http://127.0.0.1:8080/user,'user'则是BASE_URL">
          <a-input v-model="form.baseUrl"
                   placeholder="请输入"></a-input>
        </a-form-model-item>
        <!-- 验证类型 -->
        <a-form-model-item label="验证类型"
                           prop="validationType">
          <a-select ref="select"
                    v-model="form.validationType"
                    placeholder="请选择"
                    @change="validationTypeChange">
            <a-select-option value="0">无</a-select-option>
            <a-select-option value="1">OAUTH2</a-select-option>
            <a-select-option value="2">JWT</a-select-option>
            <!-- <a-select-option value="3">API秘钥</a-select-option> -->
          </a-select>
        </a-form-model-item>
        <!-- 选择auth2 JWT-->
        <template v-if="['1', '2'].includes(form.validationType)">
          <a-form-model-item label="参数位置"
                             prop="parameterPosition"
                             help="header是位于http请求头部的参数，query是位于url地址后面的参数">
            <a-select v-model="form.parameterPosition">
              <a-select-option value="1">Header</a-select-option>
              <a-select-option value="2">Query</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="token参数名称"
                             prop="parameterKey"
                             help="指定鉴权token的名称，例：access_token，token等">
            <a-input v-model="form.parameterKey"
                     placeholder="请输入"></a-input>
          </a-form-model-item>
        </template>

        <a-form-model-item label="描述"
                           prop="detail">
          <a-textarea v-model="form.detail"
                      placeholder="请输入"></a-textarea>
        </a-form-model-item>

        <div style="text-align:center">
          <ZOkButton @click="handleSave('ruleForm')"></ZOkButton>
        </div>
      </a-form-model>
    </div>
    <div class="class_name"
         v-if="idNum">
      <a-divider orientation="left">接口管理</a-divider>
      <div class="form-list">
        <div class="public-list">
          <div class="public-list-tools">
            <a-row type="flex"
                   justify="end"
                   style="margin-bottom:20px">
              <a-col flex="1">
                <a-button type="primary"
                          icon="plus"
                          action
                          @click="handleEdit('')">
                  新增
                </a-button>
              </a-col>
              <a-col :span="5"
                     style="display:flex;">
                <a-input-search placeholder="请输入关键词查询"
                                style="width: 400px"
                                v-model="params.keyWord"
                                allowClear
                                @search="search" />
              </a-col>
            </a-row>
          </div>
          <div class="public-list-panel">
            <a-table :columns="columns"
                     :data-source="dataList"
                     customCell="center"
                     :rowKey="record => record.id"
                     customHeaderCell="center"
                     :pagination="pagination"
                     @change="setPagination">
              <!-- 状态改变 -->
              <template slot="stutas"
                        slot-scope="text, record">
                <a-tag v-if="text != '1'"
                       color="red"
                       style="cursor: pointer"
                       @click="statusChange(record)">停用</a-tag>
                <a-popconfirm v-else
                              title="停用将会导致该接口不可用，确认停用吗？"
                              ok-text="是"
                              cancel-text="否"
                              @confirm="statusChange(record)">
                  <a-tag color="green"
                         style="cursor: pointer">启动</a-tag>
                </a-popconfirm>
              </template>
              <template slot="requestMethod"
                        slot-scope="text">
                <span v-if="text == '1'">GET</span>
                <span v-if="text == '2'">POST</span>
              </template>
              <template slot="operation"
                        slot-scope="text, record">
                <a-button type="link"
                          size="small"
                          @click="handleEdit(record)">
                  编辑
                </a-button>
                <a-divider type="vertical" />
                <a-popconfirm title="确定是否删除"
                              ok-text="是"
                              cancel-text="否"
                              @confirm="confirm(record.id)">
                  <a-button type="link"
                            size="small">
                    删除
                  </a-button>
                </a-popconfirm>
              </template>
            </a-table>
          </div>
        </div>
      </div>
    </div>
  </page-card>
</template>

<script>

import { saveOrUpdateFormInfo, connectorInfo, connectorinterfacePage, connectorinterfaceDeleteIds, updateState } from '../../api/connector-manage'
import { ZOkButton } from '@zh/components-ant'

export default {
  name: 'YfConnectorEdit',
  components: { ZOkButton },
  extends: null,
  mixins: [],
  props: {},
  data () {
    return {
      // 表格配置
      dataList: [],
      labelCol: { span: 6 },
      wrapperCol: { span: 12 },
      // 表单数据
      form: {
        validationType: '0',
        requestProtocol: '1',
        parameterPosition: undefined,
        parameterKey: undefined
      },
      rules: {
        name: [{
          required: true, message: '请输入表单名称', trigger: 'blur'
        }
          //  { validator: (rule, value, callback) => this.handleConfirmSkuId(rule, value, callback, '输入有误，不能输入空格') }
        ],
        provider: [{
          required: true, message: '请输入表单编码', trigger: 'blur'
        }],
        ipAddr: [{
          required: true, message: '请选择应用', trigger: 'change'
        }],
        validationType: [{
          required: true, message: '请选择验证类型', trigger: 'blur'
        }],
        parameterPosition: [{
          required: true, message: '请选择参数位置', trigger: 'blur'
        }],
        parameterKey: [{
          required: true, message: '请输入token参数名称', trigger: 'blur'
        }],
        baseUrl: [{
          required: true, message: '请选择应用', trigger: 'change'
        }]
      },
      columns: [{
        title: '接口名称',
        dataIndex: 'name',
        key: 'name',
        align: 'left'
      }, {
        title: '描述',
        dataIndex: 'detail',
        key: 'detail',
        align: 'left'
      }, {
        title: '请求方式',
        dataIndex: 'requestMethod',
        key: 'requestMethod',
        scopedSlots: { customRender: 'requestMethod' },
        align: 'left'
      }, {
        title: '接口地址',
        dataIndex: 'interfaceAddr',
        key: 'interfaceAddr',
        align: 'left'
      }, {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        align: 'left'
      }, {
        title: '状态',
        key: 'state',
        dataIndex: 'state',
        scopedSlots: { customRender: 'stutas' },
        align: 'center'
      }, {
        title: '操作',
        key: 'operation',
        width: 220,
        scopedSlots: { customRender: 'operation' },
        align: 'center'
      }],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: total => `共 ${total} 条` // 显示总数
      },
      params: {
        keyWord: ''
      }
    }
  },
  computed: {},
  watch: {},
  created () {
    this.idNum = this.$route.query.id
    if (this.idNum != '') {
      this.getInfoByID(this.idNum)
      this.getList()
    }
  },
  methods: {
    confirm (id) {
      connectorinterfaceDeleteIds([id]).then(res => {
        this.message.success('删除成功')
        this.getList()
      })
    },
    validationTypeChange () {
      this.form.parameterPosition = undefined
      this.form.parameterKey = undefined
    },
    handleEdit (record) {
      const { id = '' } = record
      const connectorId = this.idNum = this.$route.query.id
      this.$router.push({
        path: '/connector/apiedit',
        query: { id, connectorId, ipAddr: this.form.ipAddr }
      })
    },
    // 搜索
    search () {
      this.pagination.current = 1
      this.getList()
    },
    // 列表数据
    getList () {
      let param = {
        keyWord: this.params.keyWord,
        connectorId: this.$route.query.id,
        page: {
          current: this?.pagination?.current,
          size: this?.pagination?.pageSize
        }
      }
      connectorinterfacePage(param).then(res => {
        this.dataList = res.records || []
        this.pagination.current = parseInt(res.current)
        this.pagination.total = parseInt(res.total)
        this.pagination.pageSize = parseInt(res.size)
      })
    },
    setPagination (pagination) {
      this.pagination = pagination
      this.getList()
    },
    // 状态改变
    statusChange (record) {
      const { state, ...other } = record
      let val = {
        ...other,
        state: state == '0' ? '1' : '0'
      }
      updateState(val).then((res) => {
        this.message.success('操作成功')
        this.getList()
      })
    },
    // 输入验证：不允许输入空格
    handleConfirmSkuId (rule, value, callback, massageTip) {
      if (value.indexOf(' ') > -1) {
        callback(massageTip)
      } else {
        callback()
      }
    },
    // 保存
    handleSave () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const val = {
            ...this.form,
            state: this?.form?.id ? this.form.state : '1'
          }

          saveOrUpdateFormInfo(val).then((response) => {
            this.message.success(this.idNum ? '修改成功！' : '新增成功！')
            if (!this.idNum) {
              this.$router.replace({
                path: '/connector/edit',
                query: { id: response }
              })
            } else {
              this.getInfoByID(this.idNum)
            }
          })
        }
      })
    },
    // 根据id返回详情
    getInfoByID (id) {
      connectorInfo(id).then(response => {
        const { connectorAuthPo, ...other } = response
        // 处理应用信息
        this.form = {
          ...connectorAuthPo,
          ...other
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>